﻿using AutoMapper;
using B.S.Database.Domain.Entity;
using B.S.Database.ErrorCode;
using B.S.Database.Interface.Interface;
using B.S.Database.Write.Api.Application.Commands.Breeding;
using MediatR;

namespace B.S.Database.Write.Api.Application.CommandHandler.Breeding
{
    public class BreedingCreateCommandHandler : IRequestHandler<BreedingCreateCommands, Apiresult<object>>
    {
        private readonly IBaseResotity<Breeding_Information> breedingRepo;
        private readonly IMapper mapper;

        public BreedingCreateCommandHandler(IBaseResotity<Breeding_Information> BreedingRepo,IMapper mapper)
        {
            breedingRepo = BreedingRepo;
            this.mapper = mapper;
        }
        public Task<Apiresult<object>> Handle(BreedingCreateCommands request, CancellationToken cancellationToken)
        {
            Apiresult<object> res = new Apiresult<object>();
            using (var tran = breedingRepo.Db.Database.BeginTransaction())
            {
                try
                {
                    // 唯一性校验：如果存在则修改，否则添加
                    var exists = breedingRepo.GetAll().FirstOrDefault(x => x.TraceabilityId == request.TraceabilityId);
                    if (exists != null)
                    {
                        // 直接更新 exists 的属性
                        // 请将下方字段替换为你的实际字段
                        exists.Breed_Type = request.Breed_Type;
                        exists.Source_Origin = request.Source_Origin;
                        exists.Feeding_Days = request.Feeding_Days;
                        exists.Feed_Brand = request.Feed_Brand;
                        exists.Breeding_Supervisor = request.Breeding_Supervisor;
                        exists.Release_Date = request.Release_Date;
                        // 例如：
                        // exists.SomeField = request.SomeField;
                        // exists.AnotherField = request.AnotherField;
                        breedingRepo.Update(exists);
                        res.Code = ApiEnums.成功;
                        res.Message = "已存在，执行修改操作";
                    }
                    else
                    {
                        // 添加
                        var list = mapper.Map<Breeding_Information>(request);
                        breedingRepo.Add(list);
                        res.Code = ApiEnums.成功;
                        res.Message = "添加成功";
                    }
                    tran.Commit();
                }
                catch (Exception)
                {
                    res.Code = ApiEnums.错误;
                    res.Message = ApiEnums.错误.ToString();
                    tran.Rollback();
                    throw;
                }
            }
            return Task.FromResult(res);
        }
    }
}
